/*
 * @Author: aili
 * @Date: 2023-12-21 22:15:14
 * @LastEditTime: 2023-12-22 22:21:24
 * @LastEditors: aili
 * @Description:
 * @FilePath: /vue3admin/src/http/request.js
 *
 */

import service from './service'
import config from '@/config/ipConfig'
import { ElLoading } from 'element-plus'
import { getDateTime } from './dateUtils'
export function request(param) {
  console.log(param, 'param')
  let params = {}
  params = setpcBody(param)
  let loadingObj = null
  const loadingText = param.data && param.data.requestBody && param.data.requestBody.loadingText
  if (!params.loading) {
    loadingObj = ElLoading.service({
      lock: true,
      text: loadingText ? loadingText : 'Loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
  }

  return new Promise((resolve, reject) => {
    service(config[params.ip ? params.ip : 'serverPath'] + params.url, {
      ...params
    })
      .then((res) => {
        if (!params.loading) {
          loadingObj.close()
        }
        resolve(res)
      })
      .catch((err) => {
        if (!params.loading) {
          loadingObj.close()
        }
        reject(err)
      })
  })
}

function setpcBody(params) {
  const randomNum = Math.floor(Math.random() * 900000) + 100000
  const tradeSeq = `${getDateTime(new Date(), 'yyyyMMddhhmmssSSS')}${randomNum}`
  console.log(tradeSeq)

  const requestHeader = {
    tradeType: 'WEBSITE', //交易类型
    tradeSeq, //交易流水号
    tradeDate: getDateTime(new Date(), 'yyyy-MM-dd '), //日期
    tradeTime: getDateTime(new Date(), 'hh:mm:ss'), //时间
    operatorId: localStorage.getItem('usercode'), //代理人工号，从app中获取
    key: '14:41:08',
    transChnl: 'TXCDPC' //系统来源-出单平台
  }
  console.log(requestHeader)
  const data = {
    requestHeader,
    requestBody: params.data ? params.data : {}
  }
  params.data = data
  return params
}
